package pers.cocoadel.springcloud.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.cocoadel.springcloud.dao.AccountDao;
import pers.cocoadel.springcloud.domain.Account;
import pers.cocoadel.springcloud.service.AccountService;

import java.math.BigDecimal;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService
{
    private final AccountDao accountDao;

    @Autowired(required = false)
    public AccountServiceImpl(AccountDao accountDao)
    {
        this.accountDao = accountDao;
    }

    @Transactional
    @Override
    public void decrease(Long userId, BigDecimal count)
    {
        Account account = accountDao.getByUserId(userId);
        if (account.getTotal().compareTo(count) < 0)
        {
            throw new IllegalArgumentException("余额不足");
        }

        BigDecimal used = account.getUsed().add(count);
        BigDecimal residue = account.getResidue().subtract(count);
        accountDao.update(userId, used, residue);
        throw new IllegalArgumentException("有问题");
    }
}
